import {Data, ResultData} from '@/components/CacheImg/utils/CacheImgWorker'
// 在生产构建中将会分离出 chunk
import CacheImgWorker from './utils/CacheImgWorker?worker'
import loadingImg from "@/assets/gif/5dadd6e959321e9fb3639aa848cbc2fc.gif"
import PromiseWorker from "promise-worker";
const cacheImgWorker = new PromiseWorker(new CacheImgWorker())

export interface ImgItem {
  url?: string;
  cacheUrl?: string;
  img?: HTMLImageElement;
  cacheId?: string;
}

/**
 * 主动清空图片缓存
 */
export function clearImgCache() {
  return cacheImgWorker.postMessage({
    func: 'beforeunload',
    params: ''
  } as Data)
}

export function setImgSrc(imgs: ImgItem[], url: string, cacheUrl: string) {
  imgs.forEach(item=>{
    if(item.cacheUrl === cacheUrl) {
      if (url === 'loading') {
        // 给item的url尽心赋值很重要，不然就会出现url错误并且在页面上怎么操作都无法被修正
        item.url = loadingImg
        item.img.src = loadingImg
      } else {
        item.url = url
        item.img.src = url
      }
    }
  })
}

function imgGetUrl(imgs: ImgItem[], img: HTMLImageElement, url: string, cacheId: string, isSource: boolean) {
  const find = imgs.find(i => i.cacheId === cacheId)
  if (find) {
    if (find.url === 'loading') {
      // 第二次加载了就提前
      cacheImgWorker.postMessage({
        func: "toFirstNest",
        params: url,
      } as Data)
      find.img.src = loadingImg
      return;
    }
    if (find.url) {
      find.img.src = find.url
      return;
    }
  } else {
    let item: ImgItem = {
      url: 'loading',
      cacheUrl: url,
      cacheId,
      img,
    }
    imgs.push(item)
    cacheImgWorker.postMessage({
      func: "getItem",
      params: url,
      cacheId,
      isSource
    } as Data).then((data: ResultData)=>{
      if(!data) {
        return
      }
      if (data.dir === 'getUrlFinished') {
        if(data.isSource) {
          setImgSrc(useCacheImg.imgsSource, data.urlSource, data.cacheUrl)
        } else {
          setImgSrc(useCacheImg.imgs, data.url, data.cacheUrl)
        }
      }
    })
    img.src = loadingImg
  }
}

async function imgsDelTask(imgs: ImgItem[], cacheId: string) {
  const findIndex = imgs.findIndex(i => i.cacheId === cacheId)
  let delImgId = ''
  if (findIndex > -1) {
    delImgId = imgs.splice(findIndex, 1)[0].cacheUrl
  }
  return cacheImgWorker.postMessage({
    func: "delTask",
    params: delImgId,
    cacheId,
  } as Data)
}

export const useCacheImg = {
  imgs: [] as ImgItem[], // 一级缓存
  imgsSource: [] as ImgItem[], // 缓存原图
  /**
   * @param img
   * @param url 图片的url
   * @param cacheId
   * @param zipAndCache 是否开启压缩并缓存
   */
  getUrl(img: HTMLImageElement, url: string, cacheId: string, zipAndCache: boolean = true) {
    if (!img) {
      return
    }
    if (zipAndCache === false) {
      imgGetUrl(this.imgsSource, img, url, cacheId, true)
      return;
    }
    imgGetUrl(this.imgs, img, url, cacheId, false)
  },
  delTask(cacheId) {
    return Promise.all([
      imgsDelTask(this.imgs, cacheId),
      imgsDelTask(this.imgsSource, cacheId)
    ])
  }
}
